package org.ssm.demo.Thread;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.ssm.demo.entity.User;
import org.ssm.demo.service.IUserService;
import org.ssm.demo.utils.SpringContentUtil;

import java.util.List;
import java.util.concurrent.Callable;

import static org.ssm.demo.utils.ExcelUtil.getHSSFWorkbook;

/**
 * @Author: Junerain
 * @Description:
 * @Date:Created in 9:29 2018/5/21
 * @Modified By:
 */
public class MyTaskExportExcelCall implements Callable<HSSFWorkbook> {
    private int taskIndex = 0;
    private int offset = 0;
    private int endIndex = 0;
    private String fileName = "";
    private String sheetName = "";
    private String[] title = null;
    public HSSFWorkbook wb = null;

    public  MyTaskExportExcelCall(int num,int offset,int endIndex,String fileName,String sheetName,String[] title){
        this.taskIndex = num;
        this.offset = offset;
        this.endIndex = endIndex;
        this.fileName = fileName+".xls";
        this.sheetName = sheetName;
        this.title = title;
    }
    @Override
    public HSSFWorkbook call() throws Exception {
        IUserService userService = SpringContentUtil.getBean("userService");//解决多线程环境中，spring无法调用service、dao的问题，自己写个获取bean的工具类
        if(taskIndex != endIndex){
            System.out.println("现在导出任务的开始下标： "+taskIndex);
//            IUserService userService = SpringContentUtil.getBean("userService");
            List<User> userlist = userService.getLimit(taskIndex,offset);
            if(userlist !=null){
                wb = getHSSFWorkbook(fileName,sheetName,title,getContent(userlist,title), wb);
            }else{
                System.out.println(taskIndex+"到"+(taskIndex+offset)+"的获取结果为空");
            }
            System.out.println("至 "+(taskIndex+offset)+"执行完毕");
        }else {
            System.out.println("最后一个导出任务的开始下标： "+taskIndex);
            List<User> userlist = userService.getLimit(taskIndex,offset);
            if(userlist !=null){
                wb = getHSSFWorkbook(fileName,sheetName,title,getContent(userlist,title), wb);
            }else{
                System.out.println(taskIndex+"到"+(taskIndex+offset)+"的获取结果为空");
            }
            System.out.println("最后一个导出任务至 "+(taskIndex+offset)+"执行完毕");
        }
        return wb;
    }

    public String[][] getContent(List<User> userlist,String[] title){
        //内容
        String[][] content = new String[userlist.size()][];
        for(int i = 0;i<userlist.size();i++){
            content[i] = new String[title.length];
            User obj = userlist.get(i);
            content[i][0] = obj.getId().toString();
            content[i][1] = obj.getUserName();
            content[i][2] = obj.getPassword();
            content[i][3] = obj.getAge().toString();
        }
        return content;
    }
}
